﻿using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace DevManager.Services;

public static class InstallService
{
    /// <summary>
    /// 下载
    /// </summary>
    /// <param name="url">URL</param>
    /// <param name="path">路径</param>
    public static async Task DownloadFromUrlAsync(string url, string path)
    {
        using var client = new HttpClient();
        var response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();
        
        var file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);

        await response.Content.CopyToAsync(file);
        file.Close();
        FileInstall(path);
    }

    /// <summary>
    /// 从指令安装
    /// </summary>
    /// <param name="order">指令</param>
    public static async Task<string> OrderInstall(string order)
    {
        var a = new Process();
        a.StartInfo.FileName = "cmd.exe";
        a.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
        a.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
        a.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
        a.StartInfo.RedirectStandardError = true; //重定向标准错误输出
        a.Start();
        await a.StandardInput.WriteLineAsync(order); //指令
        a.StandardInput.Close();

        return await a.StandardOutput.ReadToEndAsync(); //输出
    }

    /// <summary>
    /// 从文件安装
    /// </summary>
    /// <param name="path">路径</param>
    public static void FileInstall(string path)
    {
        Process.Start( new ProcessStartInfo { FileName = path, UseShellExecute = true } );
    }
}